<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }"
      :default-params="{ status:'0' }" @submit="handleSeachTable">
      <t-col :span="3">
        <t-form-item label="收货人" name="consignee">
          <t-input v-model:value="params.consignee" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="收货地址" name="deliverGoodsAddress">
          <t-input v-model:value="params.deliverGoodsAddress" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="支付状态" name="status">
          <t-select v-model:value="params.status" :options="dictionaryStore.get('pay_status')" clearable
            filterable placeholder="" />
        </t-form-item>
      </t-col>
    
     
  
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table 
      ref="customTableRef" 
      row-key="id" 
      :columns="columns" 
      :api="getSingleProductCollection"
      column-controller-key="productCollection"
      :foot-data="footData"
      :on-before-set-data="handleTableSetData"
      >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-radio-group v-model="defaultCompany" theme="button" @change="handleCompanyChange">
            <t-radio-button :value="_.id" v-for="_ in companyList">{{ _.name }}</t-radio-button>
          </t-radio-group>
        </div>
      </template>
      <template #deliverGoodsTime="{ row }">
        {{ row.deliverGoodsTime?dayjs(row.deliverGoodsTime).format('YYYY-MM-DD'):'' }}
      </template>
      <template #placeAnOrderTime="{ row }">
        {{ row.placeAnOrderTime?dayjs(row.placeAnOrderTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
      </template>
      <template #songGuiziTime="{ row }">
        {{ row.songGuiziTime?dayjs(row.songGuiziTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
      </template>
      <template #acceptanceCheckTime="{ row }">
        {{ row.acceptanceCheckTime?dayjs(row.acceptanceCheckTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
      </template>
      <template #status="{ row }">
        {{ dictionaryStore.analysis('pay_status', row.status) }}
      </template>
      <template #productContractPrice="{ row }">
        {{ row.productContractPrice.toFixed(2) }}
      </template>
      <template #amountCollected="{ row }">
        <amount-received-dialog
          :single-product-contract-id="row.id"
          :order-id="row.orderId"
          :amount-collected="row.amountCollected"
          @refresh="handleRefreshTable" />
      </template>
      
      <template #operation="{ row }">
        <t-space break-line>
          <update-pay-status-dialog :id="row.id" @request-success="handleDialogRequestSuccess"/>
          <view-contract-dialog :id="row.id" :order-id="row.orderId"/>
        </t-space>
      </template>
    </custom-table>

  </t-card>
</template>

<script lang="ts">
export default {
  name: 'productCollectionList',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, onMounted, onUpdated, ref, useTemplateRef } from 'vue';

import { getSingleProductCollection } from '@/api/finance/single-collection';
import { getCompanyList } from '@/api/system/dept';
import { propertyManageCRUD } from '@/api/config/property';
import AmountReceivedDialog from './components/AmountReceivedDialog.vue';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import UpdatePayStatusDialog from './components/UpdatePayStatusDialog.vue';
import ViewContractDialog from './components/ViewContractDialog.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import disposableParams from '@/utils/disposableParams';
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 公司列表
const companyList = ref([]);
// 默认公司
const defaultCompany = ref()
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = [{ id: null, name: '全部公司' }, ...data];
      defaultCompany.value = null
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetCompanyList();

// 公司切换
const handleCompanyChange = () => {
  handleInitTable();
};
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
const table = ref([])
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  data.forEach((item: any) => {
    if(!item.productContractPrice) {
      item.productContractPrice=0
    }
    if(!item.amountCollected) {
      item.amountCollected=0
    }
    item.amountUnreceived = (item.productContractPrice - item.amountCollected).toFixed(2)
  })
  table.value =data
  return data;
};
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'consignee', title: '收货人' ,width: 80 },
  { colKey: 'deliverGoodsAddress', title: '收货地址', width: 180, ellipsis:true },
  { colKey: 'deliverGoodsTime', title: '送货时间', width:100},
  { colKey: 'productContractPrice', title: '合同金额', width:100},
  { colKey: 'amountCollected', title: '已收金额', width:100},
  { colKey: 'amountUnreceived', title: '未收金额', width:100},
  { colKey: 'placeAnOrderTime', title: '下单时间', width:160},
  { colKey: 'songGuiziTime', title: '送柜子时间', width:160},
  { colKey: 'acceptanceCheckTime', title: '验收时间', width:160},
  { colKey: 'status', title: '支付状态', width:80},
  { colKey: 'operation', title: '操作', width: 180, fixed: 'right' },
];
const handleSeachTable=(params:any) =>{
  disposableParams.set('to-do-tree-jump-params', {
      orderIds: '',
    });
  handleInitTable()
}
// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  const params = { 
    orderIds: toDoTreeJumpParams.orderIds,
    ...customSearchRef.value.params, 
    companyId: defaultCompany.value 
  };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable();
})
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 计算汇总值
const calculateSummary = (colKey: string) => {
  return table.value.reduce((sum, row) => sum + (parseFloat(row[colKey]) || 0), 0).toFixed(2);
};
// 普通表尾数据
const footData = computed(() => {
  return [
    {
      consignee: '汇总',
      productContractPrice: calculateSummary('productContractPrice'),
      amountCollected: calculateSummary('amountCollected'),
      amountUnreceived: calculateSummary('amountUnreceived'),
    },
  ];
});
</script>

<style lang="less" scoped>
:deep(.t-radio-group .t-radio-button) {
  border: none;
  border-radius: 18px !important;
  margin-left: 11px;
}

:deep(.t-radio-group .t-radio-button.t-is-checked) {
  background-color: #f2f3f5;
}
</style>
